<template>
  <div class="login-container">
    <div class="login-form-content">
      <div class="login-bg">
        <div class="header s-d-flex s-jc-space-between s-ai-center">
          <div class="flex-1 fz20 title">申请注册</div>
          <div
            class="flex-1 back s-pointer s-tar"
            @click="$router.back()"
          >返回登录</div>
        </div>
        <div class="sub-content">
          <div class="sub-title mt29 mb30">个人信息</div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="110px"
            class="demo-ruleForm w460"
          >
            <div class="sub-title mt29 mb30"></div>
            <el-form-item
              label="管理员姓名"
              prop="adminName"
            >
              <el-input
                class="w100p"
                v-model="ruleForm.adminName"
                placeholder="请输入管理员姓名"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="adminMobile"
            >
              <el-input
                class="w100p"
                v-model="ruleForm.adminMobile"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="验证码"
              prop="smsCode"
            >
              <el-input
                class="w100p"
                v-model="ruleForm.smsCode"
                placeholder="请输入验证码"
              >
                <span
                  slot="suffix"
                  class="show-pwd-code fz14 w200 s-d-block s-tar"
                  @click="getCode"
                >
                  {{showTime?`${timer}s重新获取验证码`:'获取验证码'}}
                </span>
              </el-input>

            </el-form-item>
            <el-form-item
              label="登录密码"
              prop="password"
            >
              <el-input
                :key="passwordType"
                class="w100p"
                ref="password"
                tabindex="2"
                :type="passwordType"
                v-model="ruleForm.password"
                placeholder="请输入6-12位登录密码"
              >
                <span
                  slot="suffix"
                  @click="showPwd"
                  class="show-pwd-code fz14 w200 s-d-block s-tar"
                >
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </el-input>

            </el-form-item>

          </el-form>
          <div class="sub-title mt29 mb30">单位信息</div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="110px"
            class="demo-ruleForm w460"
          >
            <el-form-item
              label="单位名称"
              prop="name"
            >
              <el-input
                class="w100p"
                v-model="ruleForm.name"
                placeholder="请输入单位名称"
              ></el-input>
            </el-form-item>
            <!-- <el-row :gutter="20"> -->
              <!-- <el-col :span="12"> -->
                <el-form-item
                  label="简称"
                  prop="shortName"
                >
                  <el-input
                    class="w100p"
                    v-model="ruleForm.shortName"
                    placeholder="请输入单位简称"
                  ></el-input>
                </el-form-item>
              <!-- </el-col> -->
              <!-- <el-col :span="12"> -->
                <el-form-item
                  label="医疗机构编码"
                  prop="code"
                >
                  <el-input
                    class="w100p"
                    v-model="ruleForm.code"
                    placeholder="请输入医疗机构编码"
                  ></el-input>
                </el-form-item>
              <!-- </el-col>
              <el-col :span="12"> -->
                <el-form-item
                  label="医疗机构编号"
                  prop="num"
                >
                  <el-input
                    v-model="ruleForm.num"
                    class="w100p"
                    disabled
                    placeholder="系统自动生成"
                  ></el-input>
                </el-form-item>
              <!-- </el-col>
              <el-col :span="12"> -->
                <el-form-item
                  label="企业信用代码"
                  prop="creditCode"
                >
                  <el-input
                    class="w100p"
                    v-model="ruleForm.creditCode"
                    placeholder="请输入企业信用代码"
                  ></el-input>
                </el-form-item>
              <!-- </el-col>
              <el-col :span="12"> -->
                <el-form-item
                  label="省市区"
                  class="w100p"
                  prop="addressCode"
                >
                  <tree-select
                    :data="treeData"
                    class="w100p"
                    :defaultProps="defaultProps"
                    :nodeKey="nodeKey"
                    ref="treeselect"
                    :checkedKeys="defaultCheckedKeys"
                    @popoverHide="popoverHide"
                  ></tree-select>
                  <!-- <el-cascader
              class="w100p"
              v-model="ruleForm.addressCode"
              clearable
              :props="props"
              placeholder="请选择省市区"
              @change="handleLocationsChange"
            ></el-cascader> -->
                </el-form-item>
              <!-- </el-col>
              <el-col :span="12"> -->
                <el-form-item
                  label="详细地址"
                  prop="address"
                >
                  <el-input
                    class="w100p"
                    v-model="ruleForm.address"
                    placeholder="请输入详细地址"
                  ></el-input>
                </el-form-item>
              <!-- </el-col>
              <el-col :span="24"> -->
              
              <!-- </el-col> -->
              <el-form-item class="s-tac">
                <el-button
                  type="primary"
                  class="w100p mt20"
                  @click="handleSave"
                >提交申请</el-button>
              </el-form-item>
            <!-- </el-row> -->

          </el-form>
          <el-dialog
            width="560px"
            title="坐标位置"
            append-to-body
            :visible.sync="innerVisible"
          >
            <BMap
              class="h390"
              ref="bmap"
            ></BMap>
            <div
              slot="footer"
              class="dialog-footer"
            >
              <el-button
                type="primary"
                @click="handleSaveBmap()"
                size="small"
              ><i class="el-icon-circle-check ml0 mr10 el-icon--right"></i> 确 定</el-button>
              <el-button
                size="small"
                @click="innerVisible = false"
              ><i class="el-icon-circle-close ml0 mr10 el-icon--right"></i> 取 消</el-button>
            </div>
          </el-dialog>
          <!-- <el-form-item
              label="单位名称"
              prop="name"
            >
              <el-input
                v-model="ruleForm.name"
                placeholder="请输入单位名称"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="简称"
              prop="shortName"
            >
              <el-input
                v-model="ruleForm.shortName"
                placeholder="请输入单位简称"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="医疗机构编码"
              prop="code"
            >
              <el-input
                v-model="ruleForm.code"
                placeholder="请输入医疗机构编码"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="企业信用代码"
              prop="creditCode"
            >
              <el-input
                v-model="ruleForm.creditCode"
                placeholder="请输入企业信用代码"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="省市区"
              prop="addressCode"
            >
             
              <tree-select
                :data="treeData"
                class="w85p"
                :defaultProps="defaultProps"
                :nodeKey="nodeKey"
                ref="treeselect"
                :checkedKeys="defaultCheckedKeys"
                @popoverHide="popoverHide"
              ></tree-select>
            </el-form-item>
            <BMap
              class="h500 mt18 w88p"
              ref="bmap"
            ></BMap> -->

        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as areaApi from "@/api/area";
import * as userApi from "@/api/user";
import BMap from "@/components/BMap/index.vue";
import TreeSelect from "@/components/TreeSelect";
export default {
  data() {
    const validateUserPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员电话"));
      } else if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateUserName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("管理员名称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };

    const validatePwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.length > 12) {
        callback(new Error("请输入6-12位登录密码"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入医疗机构编码"));
        } else if (value.length > 22) {
          callback(new Error("医疗机构编码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateCreditCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入企业信用代码"));
      } else if (value.length > 22) {
        callback(new Error("企业信用代码长度小于22位"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入单位名称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
      ) {
        callback(new Error("单位名称不超过100个英文字符或50个汉字"));
      } else {
        callback();
      }
    };
    const validateshortName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入简称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("简称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入详细地址"));
      } else if (value && !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)) {
        callback(new Error("详细地址不超过100个英文字符或者50个汉字"));
      } else {
        callback();
      }
    };
    return {
      innerVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: false,
      },
      nodeKey: "code",
      defaultCheckedKeys: [],
      treeData: [],
      passwordType: "password",
      ruleForm: {
        address: "", //详细地址
        shortName: "",
        adminMobile: "", //管理员电话
        adminName: "", //管理员名称
        cityCode: "", //市编码
        code: "", //医院编码
        creditCode: "", //信用代码
        id: "",
        adminId: "",
        addressCode: [],
        isFreeze: 1,
        name: "", //医院名称
        provinceCode: "", //省编码
        regionCode: "", //区编码
        townCode: "", //镇编码
        password: "", //登入密码
        smsCode: "", //验证码
      },
      areaList: [], //省市区列表
      props: {
        children: "children",
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level } = node;
          if (level == 0) {
            //省
            const { data } = await areaApi.getProvinceList();
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 1) {
            const { data } = await areaApi.getCityList({
              provinceCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 2) {
            const { data } = await areaApi.getRegionList({
              cityCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 3) {
            const { data } = await areaApi.getTownList({
              regionCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: true,
              };
            });
            resolve(nodes);
          }
        },
      },
      rules: {
        name: [
          {
            required: true,
            validator: validateName,
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            validator: validateshortName,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            validator: validateCode,
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            validator: validateCreditCode,
            trigger: "blur",
          },
        ],
        addressCode: [
          {
            required: true,
            message: "请选择省市区",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            validator: validateAddress,
            trigger: "blur",
          },
        ],
        adminName: [
          {
            required: true,
            validator: validateUserName,
            trigger: "blur",
          },
        ],
        adminMobile: [
          {
            required: true,
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            validator: validatePwd,
            trigger: "blur",
          },
        ],
        smsCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
      showTime: false,
      timer: 60,
    };
  },
  components: {
    BMap,
    TreeSelect,
  },
  async mounted() {
    let _this = this;
    _this.treeData = [];
    const { data } = await areaApi.getProvinceList();
    _this.treeData = data.map((item) => {
      item.children = [];
      return item;
    });
    this.defaultCheckedKeys = [];
    this.$refs.treeselect.handleInit(this.treeData);
    // this.$refs.bmap.handleInit();
  },
  methods: {
    //获取地图数据
    handleSaveBmap(row) {
      let bMapForm = this.$refs.bmap.form;
      this.ruleForm.longitude = bMapForm.longitude;
      this.ruleForm.latitude = bMapForm.latitude;
      this.ruleForm.address = bMapForm.address;
      this.innerVisible = false;
    },
    //打开地图
    handleInnerVisible() {
      this.innerVisible = true;
      let _this = this;
      this.$nextTick(() => {
        if (_this.title == "新增医院机构") {
          _this.$refs.bmap.handleInit({});
        } else {
          _this.$refs.bmap.handleInit(_this.ruleForm);
        }
      });
    },
    popoverHide(checkedIds, checkedData) {
      this.ruleForm.addressCode = [
        checkedData.provinceCode,
        checkedData.cityCode,
        checkedData.regionCode,
        checkedData.code,
      ];
      console.log(checkedIds);
      console.log(checkedData);
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //获取验证码
    getCode() {
      if(this.showTime) {
        return
      }
      if (!this.ruleForm.adminMobile) {
        this.$message.error({
          message: "请输入手机号",
        });
        return;
      } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.ruleForm.adminMobile)) {
        this.$message.error({
          message: "电话有误，请重填",
        });
        return;
      }
      this.timer = 60;
      this.showTime = true;
      let timer = null;
      if (timer) {
        clearInterval(timer);
      }
      userApi.sendMessage({ phone: this.ruleForm.adminMobile }).then((res) => {
        if (res && res.success) {
          timer = setInterval(() => {
            if (this.timer <= 0) {
              this.showTime = false;
              clearInterval(timer);
            } else {
              this.timer--;
            }
          }, 1000);
        }
      });
    },
    //获取省市区数据
    handleLocationsChange(val) {
      this.ruleForm.addressCode = JSON.parse(JSON.stringify(val));
      this.ruleForm = Object.assign({}, this.ruleForm);
    },
    //提交申请
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // let bMapForm = this.$refs.bmap.form;
          let params = {
            address: this.ruleForm.address, //详细地址
            shortName: this.ruleForm.shortName,
            adminMobile: this.ruleForm.adminMobile, //管理员电话
            adminName: this.ruleForm.adminName, //管理员名称
            cityCode: this.ruleForm.addressCode[1], //市编码
            code: this.ruleForm.code, //医院编码
            creditCode: this.ruleForm.creditCode,
            id: this.ruleForm.id,
            adminId: this.ruleForm.adminId,
            isFreeze: this.ruleForm.isFreeze,
            name: this.ruleForm.name, //医院名称
            provinceCode: this.ruleForm.addressCode[0], //省编码
            regionCode: this.ruleForm.addressCode[2], //区编码
            townCode: this.ruleForm.addressCode[3], //镇编码
            smsCode: this.ruleForm.smsCode, //验证码
            password: this.ruleForm.password, //登入密码
            longitude: this.ruleForm.longitude,
            latitude: this.ruleForm.latitude,
          };
          userApi.hospitalBaseRegister(params).then((res) => {
            if (res && res.success) {
              this.$router.push({
                path: "/login",
              });
              this.$message.success({
                message: "后台审核中...,请稍等...",
              });
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  .el-tabs__item {
    color: #fff;
  }
  .el-input {
    display: inline-block;
    // height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item {
    margin-bottom: 24px;
    position: relative;
  }
  .el-form-item-1 {
    border: 1px solid #d7dadb;
    background: #fff;
    border-radius: 2px;
    height: 40px;
    line-height: 40px;
    color: #a5a7a8;
  }
  .login-form-content {
    width: 800px;
    min-height: 560px;
    display: flex;
    margin: 0 auto;
    padding: 45px 0;
    align-items: center;
    .login-bg {
      width: 800px;
      background: #fff;
      padding: 40px;
      border-radius: 8px;
    }
  }
}
</style>

<style lang="scss" scoped>
.demo-ruleForm {
  margin: 0 auto;
}
$bg: #34bbff;
$dark_gray: #333;
$light_gray: #333;
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  background: url("../../assets/bg.png") center center no-repeat;
  background-size: cover;
  overflow: hidden;
  display: flex;
  align-items: center;

  .login-form {
    position: relative;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    height: 40px;
    line-height: 40px;
    box-sizing: border-box;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      color: $light_gray;
      text-align: center;
      font-weight: bold;
      margin-top: 52px;
    }
    .titleEn {
      font-size: 12px;
      color: $light_gray;
      margin: 10px 0;
      text-align: center;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .show-pwd-code {
    position: absolute;
    right: 10px;
    font-size: 16px;
    color: #34bbff;
    cursor: pointer;
    user-select: none;
  }
}
.form-rright {
  background: #fff;
  margin: 10px 0;
  color: $light_gray !important;
  flex-direction: column;
  padding: 0 70px;
  box-sizing: border-box;
  width: 440px;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}
.el-tabs {
  width: 100%;
  ::v-deep .el-tabs__nav {
    width: 100%;
  }
  ::v-deep .el-tabs__item {
    width: 50% !important;
    color: #a5a7a8 !important;
    padding: 0;
    font-size: 16px;
    text-align: center;
  }
  ::v-deep .el-tabs__active-bar {
    width: 50% !important;
    background: #34bbff;
  }
  ::v-deep .is-active {
    color: #34bbff !important;
  }
  ::v-deep .el-form-item__content {
    height: 38px;
    line-height: 38px;
  }
  ::v-deep .el-input {
    height: 38px;
    line-height: 38px;
    input {
      height: 38px;
      line-height: 38px;
      box-sizing: border-box;
      color: #a5a7a8;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #7c7e82 !important;
      }
    }
  }
  .svg-icon {
    vertical-align: 0.35em;
  }
}
.color-gray {
  color: #a5a7a8 !important;
}
::v-deep .el-tabs__header {
  margin-bottom: 30px;
}
.title {
  font-weight: bold;
  color: #333;
}
.back {
  font-size: 14px;
  color: #a5a7a8;
}
.sub-title {
  font-size: 16px;
  color: #333;
}
</style>
